package main.niit.dao.impl;

import main.niit.dao.UserDao;
import main.niit.pojo.User;
import main.niit.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static jdk.nashorn.internal.objects.Global.println;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> getgpa3() throws Exception {
        Connection connection=JDBCUtils.getConnection();
        List<User> list=new ArrayList<>();
        PreparedStatement ps=null;
        ResultSet resultSet=null;

        try {
            String sql = "SELECT name, stuid, gpa FROM gpa ORDER BY gpa DESC LIMIT 3;";
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                User user = new User();
                user.setName(resultSet.getString("name"));
                user.setStuid(resultSet.getInt("stuid"));
                user.setGpa(resultSet.getInt("gpa"));
                list.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(ps,connection);
        }

        return list;

    }
    public List<User> getrecommend() throws Exception {
        Connection connection=JDBCUtils.getConnection();
        List<User> list=new ArrayList<>();
        PreparedStatement ps=null;
        ResultSet resultSet=null;
        try {
            String sql = "SELECT name,recommend FROM ads_stuInfo;";
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                User user = new User();
                user.setName(resultSet.getString("name"));
                user.setRecommend(resultSet.getString("recommend"));
                list.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(ps,connection);
        }

        return list;

    }
    public List<User> getfind(String name) throws Exception {
        Connection connection = JDBCUtils.getConnection();
        List<User> list = new ArrayList<>();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            String sql = "SELECT*FROM ads_stuInfo WHERE name LIKE '%" + name + "%'";
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while (resultSet.next()) {
                User user = new User();
                user.setName(resultSet.getString("name"));
                user.setRecommend(resultSet.getString("recommend"));
                list.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.close(ps, connection);
        }

        return list;
    }
}

